#!/usr/bin/python

"""Program for generating a cheat sheet PDF out of xml files"""
import xml.etree.ElementTree as ElementTree
import pdfbuilder
import settings


def checkValidity(xmlroot):
    """Check if xml file is valid (according to settings)"""
    if not (len(xmlroot.findall("column")) == int(settings.settingslist["doc_columns"])):
        print("Error: number of columns does not match those in settings.")
        quit()


def generate(xml):
    """Main function for PDF generation"""
    print xml
    #Read XML files in settings directory
    settings.readsettings()
    settings.settingslist["title"] = xml

    #Begin parsing the cheat sheet XML file
    tree = ElementTree.parse("cheatsheets/{name}.xml".format(name=xml))
    root = tree.getroot()
    if not (root.tag == "cheatsheet"):
        print("Error: can't find root 'cheatsheet' in xml")
        quit()
    else:
        #Extract settings from xml and apply them in settingslist
        for child in root:
            if(child.tag != "column"):
                settings.settingslist["doc_{varname}"
                .format(varname=child.tag)] = child.text

        #Check validity of xml
        checkValidity(root)

        #Extract title
        title = root.find("title").text

        #Initialize PDF
        pdfBuilder = pdfbuilder.PDFBuilder()
        pdfBuilder.initializePDF(xml, int(settings.settingslist["doc_columns"]))
        pdfBuilder.drawHeader(title)

        #Build each column
        for column in root.findall("column"):
            for module in column.findall("module"):
                #Ask pdfbuilder to print module to PDF
                pdfBuilder.drawModule(module.text)

            #Tell pdfbuilder that it should jump to the next column'"""
            pdfBuilder.nextcolumn()

        pdfBuilder.save()
